package tcu.iot.mqttupdate.service;


import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import tcu.iot.mqttupdate.dao.MQTTMapper;
import tcu.iot.mqttupdate.entity.*;
import tcu.iot.mqttupdate.utils.dateutils.DateUtils;
import tcu.iot.mqttupdate.utils.mqttutils.MqttPushClient;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class MQTTService {

    private static final Logger log = LoggerFactory.getLogger(MQTTService.class);


    public static MQTTData mqttData;

    private MqttPushClient client;

    @Resource
    private MQTTMapper mqttMapper;

    /**
     * 初始化MQTT连接
     * 前端传输配置信息，根据配置信息连接MQTT
     */
    public R initMQTT() {
        String ID = UUID.randomUUID().toString();

//        MqttPushClient.MQTT_HOST = mqtt.getMQTT_HOST();
//        MqttPushClient.MQTT_CLIENTID = ID;
//        MqttPushClient.MQTT_USERNAME = mqtt.getMQTT_USERNAME();
//        MqttPushClient.MQTT_PASSWORD = mqtt.getMQTT_PASSWORD();

        MqttPushClient.MQTT_HOST = "tcp://124.70.14.87:1883";
        MqttPushClient.MQTT_CLIENTID = ID;
        MqttPushClient.MQTT_USERNAME = "1344";
        MqttPushClient.MQTT_PASSWORD = "1344";

        client = MqttPushClient.getInstance();

        if (client != null) {
            log.info("MQTT连接成功");
            return R.ok("true", 200, "成功", "连接成功");
        } else
            return R.failed("false", 400, "失败");
    }

    /**
     * 断开MQTT服务器连接
     */
    public R disconnect() {
        client = null;
        return R.ok("true", 200, "成功断开连接", "成功断开连接");
    }

    /**
     * 订阅设备，前端传入设备订阅的ID
     * 同时检测数据库是否有相应设备的数据表，没有则创建
     */
    @SneakyThrows
    public R subscribe() {

        List<String> deviceList = mqttMapper.connectMqtt();
        if (client != null) {
            //SQLUtils.initTable(device.getDeviceName());

            for (int i = 0; i < deviceList.size(); i++) {
                client.subscribe(deviceList.get(i));
                log.info("订阅成功");
            }
            return R.ok("true", 200, "订阅成功", deviceList);
        } else {
            log.info("订阅失败");
            return R.failed("false", 400, "client或为空，请检查连接");
        }
    }

    /**
     * 实现MQTT中publish功能
     * 向指定设备发送消息
     */
//    public R publish(MQTTPublish mqttPublish) {
//        client.publish(mqttPublish.getDeviceName(), mqttPublish.getMessage());
//        return R.ok("true", 200, "发送成功", "true");
//    }

    /**
     * 返回最近一条mqtt数据
     */
//    public R getData(SubscribeDevice subscribeDevice) {
//        if (mqttData != null)
//            return R.ok("true", 200, "成功", mqttData);
//        else
//            return R.failed("false", 400, "失败");
    //List<MQTTReturn> mqttReturnList = mqttMapper.SelectData(subscribeDevice.getDeviceName());
//        if (mqttReturnList != null)
//            return R.ok("true", 200, "成功", mqttReturnList);
//        else
//            return R.failed("false", 400, "当前设备数据不存在");
//    }

    /**
     * 由mqtt回调函数调用，用于插入数据库
     */
    public void InsertData(String topic, String MQTTData) {

        mqttData = JSON.parseObject(MQTTData, MQTTData.class);

        if (mqttData != null) {
            mqttMapper.InsertData(topic, DateUtils.getDateTime(), mqttData.getTemplate(), mqttData.getPower(), mqttData.getI1(), mqttData.getI2(), mqttData.getI3(), mqttData.getI4());
            log.info("数据插入成功");
        } else
            log.info(MQTTData);
    }

    public R DeleteData() {
        mqttMapper.DeleteData("bd_eternity_101");
        return R.ok("true", 200, "成功", "删除成功");
    }
}

